package cn.aiyuan.properties;

import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;

/**
 * @author wy
 * @since  2020/9/22
 */
@Data
@Component
@ConfigurationProperties(prefix = "ali")
public class OssConfigurationProperties {

    // bucket
    private String bucketName;

    // 域名 oss-cn-chengdu.aliyuncs.com
    private String endpoint;

    // accessKeyId
    private String accessKey;

    // accessKeySecret
    private String accessKeySecret;


    // 文件上传
    public boolean upload(String filePath, String url) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        try {
            // 上传文件流。
            InputStream inputStream = new FileInputStream(filePath);
            client.putObject(bucketName, url, inputStream);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
    }
    // 重载upload
    public boolean upload(InputStream is, String url) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        try {
            // 上传文件流。
            client.putObject(bucketName, url, is);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
    }


    // 删除文件
    public boolean delFile(String path) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        String[] split = path.split("/");
        String[] newPath = Arrays.copyOfRange(split, 3, split.length);
        StringBuilder ossPath = new StringBuilder();
        for (int i = 0; i < newPath.length; i++) {
            if (i == newPath.length - 1)
                ossPath.append(newPath[i]);
            else
                ossPath.append(newPath[i]).append("/");
        }
        try {
            client.deleteObject(bucketName, ossPath.toString());
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            client.shutdown();
        }
    }


    // 获取文件路径
    public String getFileOSSUrl(String url) {
        String prefix = "https://";
        return prefix + bucketName + "." + endpoint.substring(7) + "/" +url;
    }

}
